<script setup>
import { inject, nextTick, onMounted, ref, toRaw } from 'vue'
//图标
import { IconArrowLeft } from '../icon/index.js'
//消息提示工具
import { DlMessageBox } from '../util/messagebox.js'
import DlLoading from '../components/DlLoading.vue'

//引入 api
import { userGetAddrFun, userSetDefaultAddrFun, userModifyAddrFun, userRemoveAddrFun, userAddAddrFun } from '../api/user.js'

//主菜单核心
const menuCore = inject('menuCore');
//返回
function doGoBack() {
    menuCore.back();
}

//登录用户缓存
const loginUser = inject('loginUser');
//是否登录
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        menuCore.push('/login');
        return;
    }
    isLogin.value = true;
}

// 获取用户的收货地址数据
const addrArr = ref([]);
const loading = ref(false);
const currentDefaultAddr = ref();//当前的默认地址
function doLoadData() {
    //登录后才能执行
    if(!isLogin.value) return;
    loading.value = true;
    saveModifyAddrArr = [];
    //获取收货地址数据
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            for(let i=1; i<=2; i++) {
                dataArr.push({
                    id: i, 
                    name: '张三'+i,
                    phone: '13912345678',
                    addr: '江苏南京江北新区XXX社区XX路NN号SSSS', 
                    defaultAddr: 0
                });
            }
            dataArr.push({
                id: dataArr.length+1, 
                name: '麻子',
                phone: '18912345678',
                addr: '江苏南京江北新区XXX社区XX路XX号XX', 
                defaultAddr: 1 // 1 是默认, 0 不是默认
            });

            //成功后执行以下操作
            dataArr.sort((a,b)=>{
                return b.defaultAddr == 1 ? 1 : -1;//默认地址 排第一个
            });
            dataArr.forEach(d => {
                //设置编辑状态
                d.edit = false;//不在编辑中
                //设置默认选中=false
                d.checked = d.defaultAddr == 1;
                if(d.checked) {
                    currentDefaultAddr.value = d;
                }
            });
            addrArr.value = dataArr;
            loading.value = false;
        }, 1000);
    } else {
        //请求api
        userGetAddrFun().then((result)=>{
            console.log('userGetAddrFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                let dataArr = result.data;
                //成功后执行以下操作
                dataArr.sort((a,b)=>{
                    return b.defaultAddr == 1 ? 1 : -1;//默认地址 排第一个
                });
                dataArr.forEach(d => {
                    //设置编辑状态
                    d.edit = false;//不在编辑中
                    //设置默认选中=false
                    d.checked = d.defaultAddr == 1;
                    if(d.checked) {
                        currentDefaultAddr.value = d;
                    }
                });
                addrArr.value = dataArr;
                
            } else {
                DlMessageBox.error(result.msg);
            }
            loading.value = false;
        });
    }

}

//设置默认地址
function doSelectDefaultAddr(addr) {
    if(addr.checked) {
        return;
    }
    currentDefaultAddr.value.checked = false;
    addr.checked = true;

    if (window && window.enableDl) {
        //模拟
        DlMessageBox.success('设置成功');
        //成功后执行以下操作
        let oldAddr = currentDefaultAddr.value;
        //取消默认
        oldAddr.checked = false;
        oldAddr.defaultAddr = 0;

        //设为默认
        addr.checked = true;
        addr.defaultAddr = 1;

        currentDefaultAddr.value = addr;
    } else {
        //设为默认, 请求api
        userSetDefaultAddrFun(addr.id).then((result)=>{
            //result.code = 200;//测试代码
            console.log('userSetDefaultAddrFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                let oldAddr = currentDefaultAddr.value;
                //取消默认
                oldAddr.checked = false;
                oldAddr.defaultAddr = 0;
    
                //设为默认
                addr.checked = true;
                addr.defaultAddr = 1;
    
                currentDefaultAddr.value = addr;
            } else {
                DlMessageBox.error(result.msg);
                addr.checked = false;
                currentDefaultAddr.value.checked = true;
            }
        });
    }

}

//确认修改
function doModifyAddr(index) {
    let addrObj = addrArr.value[index];
    //修改地址信息
    let params = {id: addrObj.id, name: addrObj.name, phone: addrObj.phone, addr: addrObj.addr};
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        DlMessageBox.success('修改成功');
        //成功后执行以下操作
        addrObj.edit = false;
        saveModifyAddrArr[index] = null;//清除缓存
    } else {
        //请求api
        userModifyAddrFun(params.id, params.name, params.phone, params.addr).then((result)=>{
            //result.code = 200;//测试代码
            console.log('userModifyAddrFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                addrObj.edit = false;
                saveModifyAddrArr[index] = null;//清除缓存
                //重新加载
                doLoadData();
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}
//取消修改
function doCancelAddrEdit(index) {
    //取消修改
    addrArr.value[index] = { ...toRaw(saveModifyAddrArr[index]) };
    addrArr.value[index].edit = false;
    saveModifyAddrArr[index] = null;//清空缓存
}
//暂存要修改的addr
let saveModifyAddrArr = [];
//显示修改
function doShowAddrEdit(index) {
    //展示修改
    let addr = addrArr.value[index];
    addr.edit = true;
    saveModifyAddrArr[index] = { ...toRaw(addr) };
}
//删除
function doRemoveAddr(index) {
    //删除地址信息
    let addrObj = addrArr.value[index];
    console.log('id:', addrObj.id);

    if (window && window.enableDl) {
        //模拟
        addrArr.value.splice(index, 1);
        DlMessageBox.success('删除成功');
    } else {
        //请求api
        userRemoveAddrFun(addrObj.id).then((result)=>{
            //result.code = 200;//测试代码
            console.log('userRemoveAddrFun result:', result);
            if (result.code == 200) {
                //成功后执行以下操作
                DlMessageBox.success(result.msg);
                //重新加载
                doLoadData();
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }


}

//显示新增
const addBoxHeight = ref(0);
function doShowAddrAdd() {
    if(addBoxHeight.value) {
        newAddr.value = {name:'', phone:'', addr:'', defaultAddr: 0};
    }
    addBoxHeight.value = addBoxHeight.value ? 0 : 4.7;
}
//新增
const newAddr = ref({name:'', phone:'', addr:'', defaultAddr: 0});
function doAddAddr() {
    //TODO: 新增地址信息
    let params = toRaw(newAddr.value);
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        params.id = addrArr.value.length + 1;
        addrArr.value.push(params);
        DlMessageBox.success('添加成功');
    } else {
        //请求api
        userAddAddrFun(params.name, params.phone, params.addr, params.defaultAddr).then((result)=>{
            //result.code = 200;//测试代码
            console.log('userAddAddrFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                //DlMessageBox.success('新增成功');
                //重新加载
                doLoadData();
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}
//新增的设置默认
function doSelectNewDefault() {
    let val = newAddr.value.defaultAddr;
    newAddr.value.defaultAddr = val == 1 ? 0 : 1;
}

onMounted(()=>{
    doCheckLogin();
    doLoadData();
});

</script>
<template>
    <div class="view-dl">
        <!-- 顶部 -->
        <div class="top-head-dl">
            <IconArrowLeft class="back-icon" @click="doGoBack" />
            <div class="title-dl">收货地址管理</div>
        </div>

        <div class="view-body-dl">
            <div class="add-btn-dl" @click="doShowAddrAdd" >新增地址</div>

            <div class="add-box-dl" :style="'height: '+ addBoxHeight +'rem;'">
                <div class="addr-box-dl">
                    <div class="top-dl">
                        <div class="name-dl">
                            <input type="text" class="edit-input-dl" placeholder="收件人" v-model="newAddr.name">
                        </div>
                        <div class="phone-dl">
                            <input type="text" class="edit-input-dl" placeholder="手机号" v-model="newAddr.phone">
                        </div>
                    </div>
                    <div class="middle-dl">
                        <textarea class="edit-area-dl" placeholder="收件地址" v-model="newAddr.addr"></textarea>
                    </div>
                    <div class="bottom-dl">
                        <label class="check-dl">
                            <input type="radio" class="radio-dl" :checked="newAddr.defaultAddr == 1" @click="doSelectNewDefault">
                            <div class="tip-dl" >默认地址</div>
                        </label>
                        <div class="act-dl">
                            <div class="btn-dl" @click="doAddAddr">确定</div>
                            <div class="btn-dl" @click="doShowAddrAdd">取消</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="addr-list-title-dl">已有地址列表：</div>

            <div class="addr-list-dl">
                <div class="addr-box-dl" v-for="(d,i) in addrArr" :key="d.id">
                    <div class="top-dl">
                        <div class="name-dl">
                            <div class="tip-dl" v-show="!d.edit">{{d.name}}</div>
                            <input type="text" class="edit-input-dl" v-show="d.edit" v-model="d.name">
                        </div>
                        <div class="phone-dl">
                            <div class="tip-dl" v-show="!d.edit">{{d.phone}}</div>
                            <input type="text" class="edit-input-dl" v-show="d.edit" v-model="d.phone">
                        </div>
                    </div>
                    <div class="middle-dl">
                        <div class="tip-dl" v-show="!d.edit">{{d.addr}}</div>
                        <textarea class="edit-area-dl" v-show="d.edit" v-model="d.addr"></textarea>
                    </div>
                    <div class="bottom-dl">
                        <label class="check-dl">
                            <input type="radio" class="radio-dl" name="defaultAddr" :checked="d.checked" @click="doSelectDefaultAddr(d)">
                            <div class="tip-dl">默认地址</div>
                        </label>
                        <div class="act-dl">
                            <div class="btn-dl" v-show="d.edit" @click="doModifyAddr(i)" >确定</div>
                            <div class="btn-dl" v-show="d.edit" @click="doCancelAddrEdit(i)" >取消</div>

                            <div class="btn-dl" v-show="!d.edit" @click="doShowAddrEdit(i)">编辑</div>
                            <div class="btn-dl" v-show="!d.edit" @click="doRemoveAddr(i)" >删除</div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="loadin-box-dl">
                <DlLoading v-show="loading" />
                <div class="no-more-data-dl" v-show="!loading && addrArr.length < 1">暂无数据</div>
            </div>

        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    height: 100%;
    overflow: hidden auto;
}
.top-head-dl {
    background-color: #fff;
    color: #333;
    padding: 0.2rem;
    position: sticky;
    top: 0;
    z-index: 2;
}
.top-head-dl .back-icon {
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    position: absolute;
    top: 50%;
    left: 0.2rem;
    transform: translate(0, -50%);
}
.top-head-dl .title-dl {
    font-size: 0.7rem;
    text-align: center;
}

.view-body-dl {
    padding: 0.2rem 0.2rem 1rem;
}

.add-btn-dl {
    background-color: #fff;
    color: #a00;
    padding: 0.2rem;
    text-align: center;
    font-size: 0.48rem;
    font-weight: bold;
    border-radius: 0.2rem;
    margin: 0.2rem 0;
    cursor: pointer;
}

.add-box-dl {
    margin-top: 0.2rem;
    overflow: hidden;
    transition: height 0.5s ease-in-out;
}

.addr-list-title-dl {
    margin: 0.2rem 0;
    font-weight: bold;
}

/* .addr-list-dl {
} */

.addr-box-dl {
    font-weight: bold;
    color: #333;
    background-color: #fff;
    font-size: 0.48rem;
    padding: 0.2rem;
    border-radius: 0.2rem;
    margin-bottom: 0.2rem;
}
.addr-box-dl .top-dl {
    display: flex;
    justify-content: space-between;
    height: 1rem;
}
.top-dl .name-dl {
    width: 35%;
}
.top-dl .phone-dl {
    width: 45%;
}
.top-dl .tip-dl {
    color: #333;
}
.top-dl .edit-input-dl {
    width: 100%;
    font-size: 0.48rem;
    border-radius: 0.1rem;
    padding: 0.1rem;
    box-sizing: border-box;
}

.addr-box-dl .middle-dl {
    margin: 0.2rem 0;
}
.middle-dl .tip-dl {
    color: #777;
}
.middle-dl .edit-area-dl {
    width: 100%;
    height: 1.6rem;
    font-size: 0.48rem;
    border-radius: 0.1rem;
    padding: 0.1rem;
    box-sizing: border-box;
    background-color: #fff;
    color: #333;
    resize: none;
}

.addr-box-dl .bottom-dl {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.3rem 0 0.1rem;
    border-top: 1px solid #ccc;
    font-size: 0.4rem;
}

.check-dl .radio-dl {
    width: 0.4rem;
    height: 0.4rem;
}
.check-dl .tip-dl {
    display: inline-block;
    margin-left: 0.1rem;
}
.act-dl .btn-dl {
    display: inline-block;
    margin: 0 0.4rem;
    cursor: pointer;
}

.loadin-box-dl {
    text-align: center;
    font-size: 1rem;
    color: #999;
}
.no-more-data-dl {
    font-size: 0.4rem;
}

</style>